package me.maven.plugin.remotejar;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author langle__
 * @version 1.0
 */
public class Main {

    private static final Logger logger = LogManager.getLogger(Main.class);
    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    private static String password;

    public static void main(String[] args) {
        Properties properties = new Properties();
        File file = new File("server.properties");
        if (!file.exists()) {
            properties.setProperty("server-port", "25565");
            properties.setProperty("server-dir", "");
            properties.setProperty("timeout", "3000");
            properties.setProperty("thread-size", "10");
            properties.setProperty("password", PasswordUtil.randomPassword(16));
            try {
                properties.store(Files.newOutputStream(file.toPath()), "Remote Jar");
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        } else {
            try {
                properties.load(Files.newInputStream(file.toPath()));
            } catch (IOException e) {
                logger.error(e.getMessage());
                return;
            }
        }
        password = properties.getProperty("password");
        if (password.isEmpty()) {
            logger.error("Password is empty");
            return;
        }
        int port = Integer.parseInt(properties.getProperty("server-port"));
        int timeout = Integer.parseInt(properties.getProperty("timeout"));
        int threadSize = Integer.parseInt(properties.getProperty("thread-size"));
        String directory = properties.getProperty("server-dir");
        logger.info("Server port: {}", port);
        File dir = new File(directory.isEmpty() ? System.getProperty("user.dir") : directory);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.error("Can't create server dir");
        }
        logger.info("Server dir: \"{}\"", directory);
        logger.info("Server Password: \"{}\"", password);

        ExecutorService executor = Executors.newFixedThreadPool(threadSize);

        try (ServerSocket server = new ServerSocket(port)) {
            //noinspection InfiniteLoopStatement
            while (true) {
                ClientThread client = new ClientThread(server.accept(), dir);
                client.setSoTimeout(timeout);
                logger.info("Client connected: {}:{}", client.getAddress(), client.getPort());
                executor.submit(client);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    public static Logger getLogger() {
        return logger;
    }

    public static String getPassword() {
        return password;
    }

}